import './style.less';
import { getStrFullLength, cutStrByFullLength } from '../_util/util';
import Input from 'ant-design-vue/es/input';

export default {
  name: 'LimitInput',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: Object.assign({}, Input.props, {
    prefixCls: {
      type: String,
      default: 'ant-input-limit'
    },
    // eslint-disable-next-line
    value: {
      type: String
    },
    limit: {
      type: Number,
      default: 200
    }
  }),
  data() {
    return {
      currentLimit: 0,
      focused: false
    };
  },
  watch: {
    value(val) {
      this.calcLimitNum(val);
    }
  },
  created() {
    this.calcLimitNum(this.value);
  },
  methods: {
    handleChange(e) {
      const value = e.target.value;
      const len = getStrFullLength(value);
      if (len <= this.limit) {
        this.currentLimit = len;
        this.$emit('change', value);
        return;
      } else {
        const str = cutStrByFullLength(value, this.limit);
        this.currentLimit = getStrFullLength(str);
        this.$emit('change', str);
      }
      console.error('limit out! currentLimit:', this.currentLimit);
    },
    focus() {
      this.$refs.input.focus();
      this.$emit('focus');
    },
    handleFocus(e) {
      this.focused = true;
    },
    handleBlur(e) {
      this.focused = false;
      this.$emit('blur');
    },
    calcLimitNum(val) {
      const len = getStrFullLength(val);
      this.currentLimit = len;
    },
    handlePressEnter(e) {
      this.$emit('pressEnter', e);
    }
  },
  render() {
    const { prefixCls, ...props } = this.$props;
    return (
      <div class={this.prefixCls}>
        <Input
          {...{ props }}
          ref="input"
          value={this.value}
          onChange={this.handleChange}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
          onPressEnter={this.handlePressEnter}
        ></Input>
        <span class="limit" v-show={this.focused}>
          {this.currentLimit}/{this.limit}
        </span>
      </div>
    );
  }
};
